import requests
from csv import writer
from tkinter import Tk, filedialog
from bs4 import BeautifulSoup
COLUMN_HEADERS = ("品牌","车型")
ROWS = []

url_example = "https://car.autohome.com.cn/price/list-0-0-0-0-0-0-0-0-502-0-0-0-0-0-0-1.html"
response = requests.get(url_example)
soup = BeautifulSoup(response.text, 'lxml') 

pages = soup.find_all("a", class_="item", attrs={'name': 'a_brand'})
for page in pages:
    Car_brand = page.text
    if page['href'] == '#!1':
        message = "404数据已丢失"
        row = (Car_brand, message)
        ROWS.append(row)
        
    else:
        url_prep = 'https://car.autohome.com.cn' + page['href']
        url = url_prep
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'lxml') 
        Car_types = soup.find_all("a", class_="font-bold")
        for Car_type in Car_types:
            message = Car_type.text 
            row = (Car_brand, message)
            ROWS.append(row)
    
MY_FILE = filedialog.asksaveasfilename(title="Save as...",
                                       filetypes=(("Comma Separated Values", "*.csv"),),
                                       initialfile="Homework_9.csv")#这一行的意思是首选文件名

with open(MY_FILE, "w", encoding="utf-8-sig", newline="")as csv_file:
    csv_writer = writer(csv_file)
    csv_writer.writerow(COLUMN_HEADERS)
    csv_writer.writerows(ROWS)

        
